//
//  BaseUIViewController.swift
//  elarc01
//
//  Created by elarc on 16/4/14.
//  Copyright © 2016年 elarc. All rights reserved.
//

import Foundation

class BaseUIViewController: UIViewController {
    
    let panGesture = UIPanGestureRecognizer()
    
    /// 用于记录POP动画状态的变量
    private var popstate = PopActionState.NONE
    func panGestureAction(sender: UIPanGestureRecognizer) {
        let view = self.view
        if  sender.state == UIGestureRecognizerState.Began {
//当拖动事件开始的时候
            popstate = PopActionState.NONE
//           获取拖动事件的开始点坐标
//           let location = sender.locationInView(view)
//            获取拖动事件的偏移坐标
            let translation = sender.translationInView(view!)
            
            //当偏移坐标的x轴大于0,也就是向右滑动的时候.开始做真正的动作
            if  translation.x >= 0 && self.navigationController?.viewControllers.count >= 2 {
                //开启新的转场动画控制器
                interactionController = UIPercentDrivenInteractiveTransition()
                
                //开始调用navigation的POP转场
                self.navigationController?.popViewControllerAnimated(true)
            }
        }else if  sender.state == UIGestureRecognizerState.Changed {
            //当拖动事件进行时
            
            //获取到事件的偏移坐标
            let translation = sender.translationInView(view!)
            
            if translation.x<0 {
                //如果是向左移动,就不采取动作
                return
            }
            
            //获取view的CGRect
            let b = (view?.bounds)!
            
            //计算百分比
            let d = fabs(translation.x / CGRectGetWidth(b))
            
            //设置转场动画的百分比
            interactionController?.updateInteractiveTransition(d)
        }else if sender.state == UIGestureRecognizerState.Ended {
            //当拖动事件结束时
            
            let translation = sender.translationInView(view!)
            
            //判断速率向量是否大于0, 并且拉动的距离已经过半了
            if  sender.velocityInView(view).x > 0 && translation.x > CGRectGetMidX(view.bounds)-20  {
                popstate = PopActionState.FINISH
                //完成整个动画
                interactionController?.finishInteractiveTransition()
            }else {
                popstate = PopActionState.CANCEL
                //停止转场
                interactionController?.cancelInteractiveTransition()
            }
            
            //这个地方必须设置成nil. 避免两次之间的转场冲突了
            interactionController = nil;
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()
        panGesture.addTarget(self, action: #selector(BaseUIViewController.panGestureAction(_:)))
        self.view.addGestureRecognizer(panGesture)
    }
}